package cli.menu;

/**
 * BudgetBuoy
 * 
 * Simplify your personal expense management
 * 
 * @team cs2103jan13-w15-3j
 */

//--------------------------------------------------------------

/**
 * MergeCategories Class
 * 
 * Description: 
 * 
 * 
 * @package   cli.menu
 * @author    Lai Yong Quan (A0080909Y)
 * @edited by Tan Si Ling (A0085314J)
 */

import shared.*;
import java.util.ArrayList;
import java.util.List;
import cli.tools.Process;

class MergeCategories extends Function{

	private static final String[] MERGE = {
		"-= Main Menu > Manage Categories > Merge Categories =-",
		"[b]: back [u]: undo [r]: redo [h]: home menu",
		"",
		"Select the source Category by keying in its index:"
	};

	private static final String[] SELECT = {
		"-= Main Menu > Manage Categories > Merge Categories =-",
		"[b]: back [u]: undo [r]: redo [h]: home menu",
		"",
		"Select the destination Category by keying in its index:"
	};

	private static State BACK = State.MANAGECATEGORIES;
	private static State CURRENT = State.MERGECATEGORIES;

	public static State runMenu(){

		//cli.print(MERGE);

		Category source, destination;

		Object choice = tools.selectFromList(cli.getApi().getCategoryList(), "manageCategories", MERGE);

		//if back signal sent
		if (choice == null) {
			return BACK;
		}

		// if received Instruction object (divert to another menu)
		if (choice.getClass() == State.class) {
			return (State) choice;
		}

		// last case : if choice was really the correct object
		source = (Category) choice;

		List<Category> categories = cli.getApi().getCategoryList();
		if ((categories.get(0).equals(source)))
		{
			cli.println("Unable to merge with " + source.getName() + " as the source");
			cli.println("Returning to previous menu");

			return BACK;
		}


	//	cli.print(SELECT);

		choice = tools.selectFromList(cli.getApi().getCategoryList(), "manageCategories", SELECT);

		//if back signal sent
		if (choice == null) {
			return BACK;
		}

		// if received Instruction object (divert to another menu)
		if (choice.getClass() == State.class) {
			return (State) choice;
		}

		// last case : if choice was really the correct object
		destination = (Category) choice;;

		try{
			ArrayList<Record> recordList = cli.getApi().mergeCategory(source, destination);
			// Si Ling: **Keeping Track of the Actions DONE**
			tools.action.addToUndoStack(source, destination,
					Process.MERGECATEGORIES, recordList);
		}
		catch(Exception e){
			cli.println("An error has occurred - aborting");
		}

		return CURRENT;

	}

}